﻿using Atom.NetFrame;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Atom.NetFrame
{
    /// <summary>
    /// 服务器开始
    /// </summary>
    public class ServerStart
    {
        private string m_Ip = "127.0.0.1";
        private int m_Point = 8877;
        private Socket m_ServerSocker;
        private UserTokenPool m_Pool;
        private AbsHandleCenter m_Center;

        public void Init(AbsHandleCenter center)
        {
            Console.WriteLine("帧同步服务器初始化");
            m_Pool = new UserTokenPool(20);
            for (int i = 0; i < 20; i++)
            {
                UserToken ut = new UserToken();
                m_Pool.Push(ut);
            }
            m_Center = center;
            //服务器socker
            m_ServerSocker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定ip端口
            m_ServerSocker.Bind(new IPEndPoint(IPAddress.Parse(m_Ip), m_Point));
            //开启今天连接
            m_ServerSocker.Listen(3000);
            Console.WriteLine("帧同步服务器开始接受监听");
            Thread accept = new Thread(ListenClientAccept);
            accept.Start();
        }

        private void ListenClientAccept()
        {
            while (true)
            {
                //没接收到消息之前，一直卡着
                Socket scoket = m_ServerSocker.Accept();
                //从用户池中提取一个供用户使用
                UserToken ut = m_Pool.Pop();
                ut.Init(scoket, m_Center);
                //通知应用层，开启一个链接
                m_Center.ClientConnect(ut);
            }
        }
    }
}
